<?php
namespace app\index\controller;

use think\Controller;
use think\Session;
use think\Db;
use think\captcha\Captcha;
/**
 * 登录控制器
*/
class Index extends Controller
{
	/**
	 * 登录首页
	 * **/
	public function index()
    {
    	if(input('get.param') == 'admin'){
    		$this->redirect('index/index/admin');
		}
		if(input('get.param') == 'businesslogin'){
    		$this->redirect('index/index/businesslogin');
		}
		return view('404');
    }
	
	/**
	 * 商家登录页面
	*/
	public function business()
	{
		return view('business');
	}
	/**
	 * 商家登录验证码
	 */
	public function businesscode()
	{
		$captcha = new Captcha();
		$captcha->fontSize = 30;
		$captcha->length = 4;
		$captcha->expire = 300;
		return $captcha->entry();
	}
	/**
	 * 执行商家登录
	 * @param string post.code 验证码
	 * @param string post.account 邮箱账号
	 * @param string post.password 密码
	 *
	*/
	public function businesslogin()
	{
		try{
			$code = input('post.code');
			if(!captcha_check($code)){
				throw new \PDOException('验证码错误');
			}
			$email = input('post.account');
			$password = input('post.password');
			$result = Db::table('business')->where('email',$email)->where('status',2)->find();
			if($result){
				if(encrypt($password) == $result['password']){
					Session::set('business',$result);
					$success = ['success'=>'登录成功'];
					return json($success);
				}else{
					throw new \PDOException('账号或密码错误');
				}
			}else{
				throw new \PDOException('账号不存在');
			}
		}catch (\PDOException $e){
			$error = ['error'=>$e->getMessage()];
			return json($error);
		}
	}
	
	/**
	 * 管理员登录页面
	*/
	public function admin()
	{
		return view('admin');
	}
	/**
	 * 管理员登录
	 * @param string post.username 管理员账号
	 * @param string post.password 管理员密码
	 * @param string post.code 验证码
	*/
	public function adminlogin()
	{
		try{
			$code = input('post.code');
			if(!captcha_check($code)){
				throw new \PDOException('验证码错误');
			}
			$username = input('post.username');
			$password = input('post.password');
			$result = Db::table('admin')->where('account',$username)->find();
			if($result){
				if(encrypt($password) == $result['password']){
					Session::set('adminuser',$result);
					$success = ['success'=>'登录成功'];
					return json($success);
				}else{
					throw new \PDOException('账号或密码错误');
				}
			}else{
				throw new \PDOException('账号不存在');
			}
			
		}catch (\PDOException $e){
			$error = ['error'=>$e->getMessage()];
			return json($error);
		}
	}
	/**
	 * 退出登录
	 */
	public function adminoutlogin()
	{
		Session::delete('adminuser');
		$this->redirect('index/index/admin');
	}
	/**
	 * 验证码
	 */
	public function code()
	{
		$captcha = new Captcha();
		$captcha->fontSize = 30;
		$captcha->length = 4;
		$captcha->expire = 300;
		return $captcha->entry();
	}
}
